import {
  SAVE_LOCATION,
  SAVE_SHOP_ID,
  ADD_CART,
  INIT_CART,
  REDUCE_CART,
  SAVE_SHOP_DETAIL,
  CLEAR_CART,
  CONFIRM_REMARKS,
  SAVE_USER_INFO,
  SAVE_ORDER_ADDRESS,
  SELECT_ADDRESS,
  MODIFY_AVATAR,
  MODIFY_PHONE
} from './mutation-type';
import { Local } from '@/common/storage';

export default {
  // 保存当前经纬度
  [SAVE_LOCATION](state, { lat, lng }) {
    state.lat = lat;
    state.lng = lng;
  },
  // 保存店铺ID
  [SAVE_SHOP_ID](state, id) {
    state.shop_id = id;
  },
  // 保存店铺详细
  [SAVE_SHOP_DETAIL](state, detail) {
    state.shopDetail = detail;
  },
  // 初始化购物车
  [INIT_CART](state) {
    const list = Local.get('cart');
    if (list) {
      state.cartList = list;
    }
  },
  // 添加购物车
  [ADD_CART](state, data) {
    const { shop_id, menu_id, id, name, specs, select = '', food_img } = data;

    const cart = state.cartList;
    const shop = (cart[shop_id] = cart[shop_id] || {});
    const menu = (shop[menu_id] = shop[menu_id] || {});
    const food = (menu[id] = menu[id] || {});

    if (food[specs[0].id]) {
      food[specs[0].id].num++;
    } else {
      food[specs[0].id] = {
        num: 1,
        name,
        select,
        food_img,
        // id: specs[0].id,
        price: specs[0].price,
        pack_fee: specs[0].pack_fee,
        specs
      };
    }
    state.cartList = { ...cart };
    Local.set('cart', state.cartList);
  },
  // 减少购物车
  [REDUCE_CART](state, data) {
    const { shop_id, menu_id, id, specs } = data;

    const cart = state.cartList;
    const shop = cart[shop_id] || {};
    const menu = shop[menu_id] || {};
    const food = menu[id] || {};

    if (food && food[specs[0].id]) {
      if (food[specs[0].id].num > 0) {
        food[specs[0].id].num--;
      } else {
        food[specs[0].id] = null;
      }
      state.cartList = { ...cart };
      Local.set('cart', state.cartList);
    }
  },
  // 清空购物车
  [CLEAR_CART](state, id) {
    state.cartList[id] = null;
    state.cartList = { ...state.cartList };
    Local.set('cart', state.cartList);
  },
  // 保存备注
  [CONFIRM_REMARKS](state, value) {
    state.remarkInfo = value;
  },
  // 保存用户信息
  [SAVE_USER_INFO](state, data) {
    state.userInfo = data;
  },
  // 修改用户头像
  [MODIFY_AVATAR](state, path) {
    state.userInfo.avatar = path;
  },
  [MODIFY_PHONE](state, phone) {
    state.userInfo.phone = phone;
  },
  // 保存收货地址
  [SAVE_ORDER_ADDRESS](state, data) {
    state.address_name = data;
  },
  // 保存用户选择的收货地址
  [SELECT_ADDRESS](state, data) {
    state.selectaddress = data;
  }
};
